/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved.
 * distributed with this file and available online at
 */
package com.lap.auth.domain.region;

import com.lap.auth.domain.shared.errors.UserError;
import com.lap.framework.ddd.AggregateRoot;
import com.lap.framework.exception.BizException;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

/**
 * 区域领域。
 *
 * @author Shuisheng Lao(劳水生)
 * @version 0.0.1
 */
@Getter
public class Region extends AggregateRoot {

  private final Integer id;
  private final Integer pid;
  private final String code;
  private final String name;
  private final Integer orders;
  private String pidPath;

  public Region(Integer id, Integer pid, String pidPath, String code, String name, Integer orders) {
    this.id = id;
    this.pid = pid;
    this.pidPath = pidPath;
    this.code = code;
    this.name = name;
    this.orders = orders;
  }

  public void initPidPath(Supplier<Optional<Region>> parentSupplier) {
    if (pid != null) {
      parentSupplier.get().ifPresent(parent -> changePidPath(parent.getPidPath(), parent.getId()));
    }
  }

  private void changePidPath(String pidPath, Integer id) {
    StringBuilder sb = new StringBuilder();
    if (StringUtils.isNotBlank(pidPath)) {
      sb.append(pidPath).append(",");
    }
    if (id != null) {
      sb.append(id);
    }
    this.pidPath = sb.toString();
  }

  public void canDelete(List<Region> children) {
    if (!children.isEmpty()) {
      BizException.interrupt(UserError.REGION_HAS_CHILD);
    }
  }

  public boolean isNew() {
    return (id == null);
  }
}
